package com.szly.phm.admin.exception;


import com.szly.phm.common.entity.result.CodeStatusEnum;
import com.szly.phm.common.entity.result.RootResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.szly.phm.mjadmin.controller",
        "com.szly.phm.mjgov.controller",
        "com.szly.phm.mjwork.controller",
        "com.szly.phm.qdgov.controller",
        "com.szly.phm.aqfxyp.controller",
        "com.szly.phm.hbd.controller"})
public class GlobalExceptionAdvice {

    @ExceptionHandler({BindException.class})
    public RootResponse bException(BindException be, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        return RootResponse.error(CodeStatusEnum.WRONG_PARAM.getCode(),errorMsg(be.getBindingResult()));
    }

    @ExceptionHandler({Exception.class})
    public RootResponse exception(Exception e, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        return RootResponse.error(CodeStatusEnum.FAIL.getCode(),e.getMessage());
    }

    @ExceptionHandler({PzhcisPcException.class})
    public RootResponse ppcException(PzhcisPcException ppe, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        return RootResponse.error(ppe.getCode(),ppe.getMessage());
    }

    private static String errorMsg(BindingResult result) {
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : result.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        return errorMsg.toString();
    }
}
